﻿//写的有点多余，不过作为参考应该写的全面一点，所以就不删除了
$(function () {
    window.newCount = 1;
    window.zNodes = undefined;
    try {
        window.zNodes = JSON.parse(nodes);
    } catch (e) {

    }
    
    
    
    if (zNodes == undefined || zNodes.length === 0) {
        $.fn.zTree.init($("#treeDemo"), setting);        
        window.treeObj = $.fn.zTree.getZTreeObj("treeDemo");                
    } else {        
        $.fn.zTree.init($("#treeDemo"), setting,zNodes);        
        window.treeObj = $.fn.zTree.getZTreeObj("treeDemo");                    
        //arr=$.each(zNodes,function(i,e){
            //e.children=zNodes.filter(function(b){
                //return e.id==b.pId;
            //})
        //});
        //var level1=arr.filter(function(c){return c.pId==0;});
        //addList(level1);

    }
    $('#addParent').on('click', add);
    $('#save').on('click', OnSave);
});

//js没有重写这种概念，完全是以名称来区分方法
function addList(items, parent){    
    $.each(items,function(i,e){        
        var parent2=null;
        var isParent=e.children.length>0;
        if(e.pId==0){
            parent2 = treeObj.addNodes(null, {dbId:e.dbId,Id:e.id,pId: e.pId,isParent: isParent, name:e.name,isnewadd:e.isnewadd});                        
        }else{
            parent2 = treeObj.addNodes(parent, {dbId:e.dbId,Id:e.id,pId: e.pId,isParent: isParent, name:e.name,isnewadd:e.isnewadd,level:parent.level});            
        }    
        if(e.children.length>0){
            addList(e.children,parent2);
        }
    })    
}


var setting = {
    view:{
        addHoverDom: addHoverDom,
        removeHoverDom: removeHoverDom,
        selectedMulti: false
    },
    edit: {
        enable: true, //设置可以修改,才能拖动
        showRemoveBtn: true,
        showRenameBtn: true,
        editNameSelectAll:true,        
        removeTitle: "remove",
        renameTitle: "rename",
    },
    data: {
        simpleData: {
            enable: true
        }
    },
	callback:{
		onNodeCreated:onNodeCreated,
        onRemove:onRemove,
	}
};

function add(treeNode) {
    if(treeNode==undefined)
        treeNode=null;
    else if(treeNode.dbId==undefined){
        treeNode=null;
    }

    var name = "new node" + (newCount++);
    treeNode = treeObj.addNodes(treeNode, {dbId:0,pId: 0, isParent: false, name:name,isnewadd:true});        
};

function onRemove(event,treeId,treeNode){
    arr=[];
    //需要获取他的子节点，这些都是需要删除的
    GetAllChilds(treeNode.children,0);
    arr.push(treeNode);
    $.each(arr,function(i,e){
        if(e.dbId>0){
            var nodeItem=NodeItem.createNew();
            nodeItem.dbId=e.dbId,
            nodeItem.isdelete=true,
            deleteArr.push(nodeItem);    
        }
    })
    
}

function onNodeCreated(event,treeId,treeNode){
	//修改展开小节点
	var switchico=$('#'+treeNode.tId+"_switch",$('#treeDemo'));
	if(switchico!=undefined){		
		//只能通过修改样式来修改小开关，而且一般没有必要
		switchico.css({"background-image":cusImage + "/switch.jpg"});
		//switchico.html('<img src="~/images/switch.jpg" style="width:18px;height:18px;display:inline-block"/>')
	}
	//修改小图标	
	var ico=$('#'+treeNode.tId+"_ico",$('#treeDemo'));
	if(ico!=undefined){				
		ico.removeClass('button ico_open');
		//为父节点配置不同的小图标
		if(treeNode.childs>0||treeNode.children!=undefined){
			ico.html('<img src="'+ cusImage + '/p.jpg" style="width:16px;height:16px"/>')
		}else{
			ico.html('<img src="'+ cusImage + '/th.jpg" style="width:16px;height:16px"/>')
		}
	}
	

	//修改图标后内容
	var span=$('#'+treeNode.tId+"_span",$('#treeDemo'));
	if(span!=undefined){
		//span.html('<img src="~/images/th.jpg" style="margin-left:30px;width:50px;height:20px"/>')
	}
	
}

function addHoverDom(treeId, treeNode) {
    var sObj = $("#" + treeNode.tId + "_span");
    if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
    var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
        + "' title='add node' onfocus='this.blur();'></span>";
    sObj.after(addStr);
    var btn = $("#addBtn_"+treeNode.tId);
    if (btn) btn.bind("click", function(){
        
        add(treeNode);
        return false;
    });
};
function removeHoverDom(treeId, treeNode) {
    $("#addBtn_"+treeNode.tId).unbind().remove();
};


//定义一个存储zTree节点的NodeItem对象
var NodeItem = {
    createNew: function () {
        var nodeItem = {};
        nodeItem.dbId=0;
        nodeItem.id = 0;
        nodeItem.pid = 0;
        nodeItem.deep = 0;
        nodeItem.childs = 0;
        nodeItem.name = "";
        nodeItem.sort = 0;
        nodeItem.isnewadd = false;
        nodeItem.isdelete=false;
        return nodeItem;
    }
}

//定义一个存储所有节点的集合
var deleteArr=[];
var arr = [];
var id=0;
function GetAllNodes(isfirst) {
	id=0;
    arr = [];
    if (treeObj != undefined) {
        //获取一级菜单
        var sNodes = treeObj.getNodes();
        GetAllChilds(sNodes, 0);
    }
}

function GetAllChilds(childrens, deep) {
    if (childrens != undefined) {
        for (var i = 0; i < childrens.length; i++) {       
			id++;		     
            var nodeItem = NodeItem.createNew();
			childrens[i].id=nodeItem.id=id;
            var item=childrens[i];
			
			if(item.level==0||item.getParentNode()==undefined||item.getParentNode()==null)
			{
				nodeItem.pid =0;
			}
			else
			{
				nodeItem.pid = item.getParentNode().id;
			}
            nodeItem.dbId=item.dbId;
            nodeItem.deep = deep + 1;
            nodeItem.name = item.name;
            nodeItem.sort = id;
            nodeItem.isnewadd = item.isnewadd;

            if (item.children != undefined) {
                nodeItem.childs = item.children.length;
                GetAllChilds(item.children, nodeItem.deep);
            }
            
            arr.push(nodeItem);
        }
    }
}

//保存
function OnSave() {
    try {
        msgBox.showMsgWait("正在加載中...");
        GetAllNodes();

        var data = {
            projectId:projectId,
            jsonItems: JSON.stringify(arr)
        };
        $.post(saveUrl, data, function (ajaxMsg) {
            msgBox.showMsg(ajaxMsg);
            if (ajaxMsg.status == 1) {
                location.reload();
            }
        });
        return true;
    }
    catch (e) {
        msgBox.showMsgErr("發生錯誤");
        return false;        
    }
}